package com.mytinyRPC.protocol.http;

import com.mytinyRPC.Factory.SingletonFactory;
import com.mytinyRPC.framework.Invocation;
import com.mytinyRPC.provider.LocalRegister;
import com.mytinyRPC.provider.LocalRegisterImpl;
import com.mytinyRPC.serializer.CommonSerializer;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/***
 * @Author HP
 * @Description //TODO 过程调用处理器
 **/
public class HttpServerHandler {

    private static final Logger logger = LoggerFactory.getLogger(HttpServerHandler.class);
    private static final LocalRegister localRegister;
    private final CommonSerializer serializer=CommonSerializer.getByCode(1);

    static {
        localRegister = SingletonFactory.getInstance(LocalRegisterImpl.class);
    }

    public void handle(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
        // 获取对象
        try {
            //序列化传输
            InputStream is = req.getInputStream();
            Invocation invocation= (Invocation) serializer.deserialize(is.readAllBytes(),Invocation.class);
            //找出实现类
            Class imolClass= localRegister.get(invocation.getInterfaceName());

            //获取类的方法
            Method method = imolClass.getMethod(invocation.getMethodName(),invocation.getParamTypes());
            //反射调用方法
            String result = (String) method.invoke(imolClass.newInstance(),invocation.getParams());
            //把结果返回给调用者
            IOUtils.write(result,resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}
